package cn.ldf.keepaccounts.controller;

import cn.hutool.core.lang.ClassScanner;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.ldf.keepaccounts.entity.vo.R;
import cn.ldf.keepaccounts.enums.BaseEnum;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 枚举值接口
 *
 * @author ldf
 * @code May there be no bugs in the world!
 */
@RestController
@RequestMapping("enums")
public class EnumsController {

    private static final String ENUM_PACKAGE = "cn.ldf.keepaccounts.enums";

    /**
     * 获取枚举值
     *
     * @param enumName 枚举类名(有值过滤，没值查所有)
     * @return 结果集
     */
    @GetMapping("/getListByEnumName")
    public R<?> getListByEnumName(@RequestParam(required = false) String enumName) {
        Set<Class<?>> classSet;
        if (StrUtil.isBlank(enumName)) {
            classSet = ClassScanner.scanPackage(ENUM_PACKAGE);
        } else {
            classSet = ClassScanner.scanPackage(ENUM_PACKAGE, x -> x.getSimpleName().equals(enumName));
        }
        Map<String, Map<String, String>> map = MapUtil.newHashMap();
        for (Class<?> aClass : classSet) {
            if (aClass.isEnum() && aClass.getEnumConstants().length > 0) {
                String simpleName = aClass.getSimpleName();
                Object[] enumConstants = aClass.getEnumConstants();
                Map<String, String> enumClazzMap = Arrays.stream(enumConstants).filter(x -> x instanceof BaseEnum).collect(Collectors.toMap(Object::toString, x -> ((BaseEnum) x).getDesc()));
                map.put(simpleName, enumClazzMap);
            }
        }
        return R.success(map);
    }
}
